package com.qq.BFMRSE.frame;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.qq.BFMRSE.component.extractKwProgress;
import com.qq.BFMRSE.component.fileUpDeaProgress;
import com.qq.BFMRSE.component.genEnIndexProgress;
import com.qq.BFMRSE.component.luenceProgress;
import com.qq.BFMRSE.entity.encryptedIndex;
import com.qq.BFMRSE.entity.indexTree;
import com.qq.BFMRSE.entity.wordCountInfo;
import com.qq.BFMRSE.extractWord.SelectWord;
import com.qq.BFMRSE.extractWord.luceneOperation;
import com.qq.BFMRSE.extractWord.wordTFAndIDFInfo;
import com.qq.BFMRSE.index.buildIndex;
import com.qq.BFMRSE.runnable.indexBuildRunnable;
import com.qq.BFMRSE.runnable.uploadRunnable;
import com.qq.BFMRSE.serialize.objectSerializeUtil;
import com.qq.BFMRSE.util.BFConstants;
import com.qq.BFMRSE.util.UserParamManager;

public class fileUploadFrame extends JFrame implements ActionListener,ChangeListener{
	private String userName;
	private JTabbedPane tabPane;
	private Container con;
	private JLabel lueIndexLabel; 
	private JLabel fileSetLabel ;
	private JLabel skLabel;
	private JTextField lueIndexTextF;//luence索引目录
    private JTextField fileSetTextF;//文件夹目录
	private  JTextField skTextF;
	private JButton lueIndexBtn;
	private JButton fileSetBtn;
	private JButton skBtn;
	private JFileChooser jfc;
	private JButton sureBtn;
	private SelectWord selectWord;
	private luceneOperation lOperation;
	//private luenceProgress luencePro;
	//private extractKwProgress extKwPro;
	//private genEnIndexProgress genEnInPro;
	//private fileUpDeaProgress fProgress;
	/**
	 * Create the frame.
	 */
	public fileUploadFrame(String userName) {
		this.userName=userName;
		init();
		jfc.setCurrentDirectory(new File("d://"));// 文件选择器的初始目录定为d盘
		this.setContentPane(tabPane);// 设置布局
		//this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setSize(500, 300);
        this.setTitle("文件集上传");
        this.setLocationRelativeTo(null);
        lueIndexLabel.setBounds(79, 66, 101, 20);
        lueIndexTextF.setBounds(175, 66, 120, 20);
        lueIndexBtn.setBounds(310, 66, 50, 20);
        lueIndexBtn.addActionListener(this);
        fileSetLabel.setBounds(79, 101, 101, 20);
        fileSetTextF.setBounds(175, 101, 120, 20);
        fileSetBtn.setBounds(310, 101, 50, 20);
        fileSetBtn.addActionListener(this);
        skLabel.setBounds(79, 136, 101, 20);
        skTextF.setBounds(175, 136, 120, 20);
        skBtn.setBounds(310, 136, 50, 20);
        skBtn.addActionListener(this);
        sureBtn.setBounds(202, 174,  88, 27);
        sureBtn.addActionListener(this);
        con.add(lueIndexLabel);
        con.add(fileSetLabel);
        con.add(skLabel); 
        con.add(lueIndexTextF); 
        con.add(fileSetTextF);
        con.add(skTextF);
        con.add(lueIndexBtn);
        con.add(fileSetBtn);
        con.add(skBtn);
        con.add(sureBtn );
        tabPane.add("文件集", con);
        ImageIcon imgBF=new ImageIcon("images\\BFMRSE.png");
        this.setIconImage(imgBF.getImage()); 
	}
	public void init(){
		tabPane = new JTabbedPane();// 选项卡布局
		con=new Container();
		lueIndexLabel = new JLabel("luence索引目录");
		fileSetLabel = new JLabel("文件集目录");
		skLabel=new JLabel("密钥目录");
		 lueIndexTextF = new JTextField();
		 fileSetTextF = new JTextField();
		 skTextF=new JTextField();
		 lueIndexBtn = new JButton("...");// 选择
		 fileSetBtn = new JButton("...");// 选择
		 skBtn=new JButton("...");
		 jfc = new JFileChooser();// 文件选择器
		 sureBtn = new JButton("确定");//
		 selectWord=new SelectWord();
		 lOperation=new luceneOperation();
		// luencePro=new luenceProgress();
		 //extKwPro=new extractKwProgress();
		 //genEnInPro=new genEnIndexProgress();
	}
	public static void main(String []args){
		fileUploadFrame fileUF=new fileUploadFrame("qiong");
		fileUF.setVisible(true);
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource().equals(lueIndexBtn)){
			// 处理luence索引文件夹选取
			jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);//设置只能选择文件夹
			int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
			if (state == 1) {
				return;// 撤销则返回
			} else {
				File luenceIndexFile=jfc.getSelectedFile();
				lueIndexTextF.setText(luenceIndexFile.getAbsolutePath());
			}
		}else if(e.getSource().equals(fileSetBtn)){
			// 处理上传文件夹选取
			jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
			if (state == 1) {
				return;// 撤销则返回
			} else {
				File fileSet=jfc.getSelectedFile();
				fileSetTextF.setText(fileSet.getAbsolutePath());
			}
		}else if(e.getSource().equals(skBtn)){
			// 处理密钥存储文件夹选取
			jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
			if (state == 1) {
				return;// 撤销则返回
			} else {
				File skFile=jfc.getSelectedFile();
				skTextF.setText(skFile.getAbsolutePath());
			}
		}else if(e.getSource().equals(sureBtn)){
			// 处理最终确定按钮选取
			String index=lueIndexTextF.getText();
			String filePath=fileSetTextF.getText();
			String skPath=skTextF.getText();
			if("".equals(skPath)){
				JOptionPane.showMessageDialog(null, "请选择秘钥存放目录！");
			}else{
				File skFile=new File(skPath+File.separator+BFConstants.DESKEYFILENAME);
				if(!skFile.exists()){
					JOptionPane.showMessageDialog(null, "文件加密秘钥不存在于该目录，请首先进行私钥生成操作！");
					return;
				}
			}
			if("".equals(index)||"".equals(filePath)){
				JOptionPane.showMessageDialog(null, "请选择存放目录！");
			}else{
				String upLoadIndexTreeUrl=BFConstants.URL+BFConstants.URLSPE+BFConstants.UPENCRYPTTREEURL;//上传索引树url
				String upLoadEncryptIndexUrl=BFConstants.URL+BFConstants.URLSPE+BFConstants.UPENCRYPTINDEXURL;//上传加密索引url
				String upLoadEncryptFilesUrl=BFConstants.URL+BFConstants.URLSPE+BFConstants.UPENCRYPTFILEURL;//上传加密文件url
				Thread upLoadEnFilesThread=new Thread(new uploadRunnable(upLoadEncryptFilesUrl, filePath, userName, BFConstants.UPENCRYPTFILE,skPath));
				upLoadEnFilesThread.start();
				//selectWord=new SelectWord(index, filePath,skPath);
				selectWord.setIndex(index);
				selectWord.setFilePath(filePath);
				selectWord.setSkPath(skPath);
				lOperation.setIndex(index);
				lOperation.setFilePath(filePath);
				buildIndex buIndex=new buildIndex(skPath);
				//fProgress=new fileUpDeaProgress(lOperation, selectWord, buIndex);
				//luencePro.setlOperation(lOperation);
				//luencePro.setVisible(true);
				//luencePro.getTimer().start();
				final Thread luThread=new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						lOperation.buildLuceneIndex();
						/*try {
							String wordInfoFilePath=BFConstants.WORDINFOFILE+File.separator+BFConstants.INITKEYVALUE;
							objectSerializeUtil.serialize(selectWord, wordInfoFilePath);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}//存储索引路径信息*/
					}
				});
				luThread.start();
				//extKwPro.setSelectWord(selectWord);
				final Thread extKwThread=new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							luThread.join();
							//extKwPro.getTimer().start();
							//extKwPro.setVisible(true);
							wordTFAndIDFInfo.idfMap=selectWord.getAllWordIDF();
							wordTFAndIDFInfo.tfWordInfos=selectWord.getMostPopuWord(BFConstants.A);
							wordTFAndIDFInfo.ser2Info();
							String wordInfoFilePath=BFConstants.WORDINFOFILE+File.separator+BFConstants.INITKEYVALUE;
							objectSerializeUtil.serialize(selectWord, wordInfoFilePath);
							int distinctN=wordTFAndIDFInfo.idfMap.keySet().size();
							int n=distinctN+BFConstants.DUMMUYKWYWORDCOUNT;
							int dummuyN=BFConstants.DUMMUYKWYWORDCOUNT;
							wordCountInfo wcInfo=new wordCountInfo(n, distinctN, dummuyN);
							UserParamManager.setWcInfo(wcInfo);
						} catch (IOException | InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
				extKwThread.start();
				Map<String, encryptedIndex>indexMap=new HashMap<>();//加密的索引的map;
				indexTree searchIndexTree=new indexTree();//明文索引树
				try {
					extKwThread.join();
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				List<String> fileNameList=selectWord.getAllFileName();

				//genEnInPro.setBuIndex(buIndex);
				//genEnInPro.setVisible(true);
				indexBuildRunnable genEnInRunnable=new indexBuildRunnable(skPath, fileNameList,buIndex);
				Thread genEnInThread=new Thread(genEnInRunnable);
				genEnInThread.start();
				//genEnInPro.getTimer().start();
				try {
					genEnInThread.join();
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Thread upLoadInTreThread=new Thread(new uploadRunnable(upLoadIndexTreeUrl, genEnInRunnable.getSearchIndexTree().getRoot(), 
						userName,BFConstants.UPENCRYPTTREE));
				Thread upLoadEnIndexThread=new Thread(new uploadRunnable(upLoadEncryptIndexUrl, genEnInRunnable.getIndexMap(), 
						userName, BFConstants.UPENCRYPTINDEX));
				
				upLoadInTreThread.start();
				upLoadEnIndexThread.start();
				try {
					upLoadEnIndexThread.join();
					upLoadInTreThread.join();
					upLoadEnFilesThread.join();
					JOptionPane.showMessageDialog(this, "索引构建成功，并完成上传！",
							"提示",JOptionPane.INFORMATION_MESSAGE);
					//dispose();
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		}
	}
	@Override
	public void stateChanged(ChangeEvent e) {
		// TODO Auto-generated method stub	
	}
}
